package com.open.demo.flow

import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flatMapConcat
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch

/**
 *
 * @Author: hailong.qiu hailong.qiu@xgimi.com
 * @Maintainer: hailong.qiu hailong.qiu@xgimi.com
 * @Date: 2021/8/3
 * @Copyright: 2021 www.xgimi.com Inc. All rights reserved.
 */
class NewRepository {

    private val newsRemoteDataSource by lazy { NewRemoteDataSource() }
    val favoriteLatestNews: Flow<List<String>> = newsRemoteDataSource.latestNews
        .map { news ->
            news.filter {
                it.contains("l")
            }
        }
        .onEach { news ->
            news.forEach {
                Log.d("hailong.qiu", "NewRepository new:$it")
            }
        }
        .flowOn(Dispatchers.Default)

    private val firestoreUserEventsDataSource by lazy { FirestoreUserEventsDataSource() }
    val userEvents:Flow<List<String>> by lazy { firestoreUserEventsDataSource.getUserEvents() }

    init {
        GlobalScope.launch {
            userEvents
                .flowOn(Dispatchers.IO)
                .collect { }
            // callback flow + flatMapConcat  整合多个 callback 的处理方法
//                .flatMapConcat { }
        }

    }
}